package me.yuzho.study.concurrency;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class SimplePriorities implements Runnable {
    
    private int countDown = 5;
    private volatile double d; // No compile optimization
    
    private int priority;
    
    public SimplePriorities(int priority) {
        this.priority = priority;
    }
    
    

    @Override
    public String toString() {
        return String.format("%s: %d", Thread.currentThread(), countDown);
    }



    @Override
    public void run() {
        // set priority before run
        Thread.currentThread().setPriority(this.priority);
        
        while (true) {
            // Run an expensive, interruptable operation:
            for(int i=0; i<100000; i++) {
            //IntStream.range(0, 100000).forEach(i -> {
                d += (Math.PI + Math.E) / (double)(i);
                
                if(i % 1000 == 0) {
                    Thread.yield();
                }
            //});
            }
            
            System.out.println(this);
            
            if(--countDown == 0) {
                return;
            }
        }
    }

    public static void main(String [] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        
        IntStream.range(0, 5).forEach(i -> {
            exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
        });
        
        exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
        
        exec.shutdown();
    }
}
